<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"inkgn.gitee.io","root":"/","scheme":"Muse","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}};
  </script>

  <meta name="description" content="先填个坑写之前先填个坑，因为一时疏忽，把组将名称和组件components命名重复，导致一个十分诡异的bug，当我数据请求后在我的页面内完完全全复制了一份我当前页面的内容，毫无理由，十分恐怖，当我再次想重现当日情景时发现实现不了!">
<meta property="og:type" content="article">
<meta property="og:title" content="记录一次Vue组件缓存（keep-alive）">
<meta property="og:url" content="https://inkgn.gitee.io/2021/11/03/article28/index.html">
<meta property="og:site_name" content="静水深流">
<meta property="og:description" content="先填个坑写之前先填个坑，因为一时疏忽，把组将名称和组件components命名重复，导致一个十分诡异的bug，当我数据请求后在我的页面内完完全全复制了一份我当前页面的内容，毫无理由，十分恐怖，当我再次想重现当日情景时发现实现不了!">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2021-11-03T04:49:45.000Z">
<meta property="article:modified_time" content="2022-12-06T02:15:57.304Z">
<meta property="article:author" content="yinks">
<meta property="article:tag" content="Vue">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="https://inkgn.gitee.io/2021/11/03/article28/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>记录一次Vue组件缓存（keep-alive） | 静水深流</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">静水深流</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/categories" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
        <li class="menu-item menu-item-motto">

    <a href="/motto/motto" rel="section"><i class="fa fa-book fa-fw"></i>古训</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/me" rel="section"><i class="fa fa-user fa-fw"></i>关于</a>

  </li>
  </ul>
</nav>




</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://inkgn.gitee.io/2021/11/03/article28/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="https://blog-1253246719.cos.ap-chengdu.myqcloud.com/blog/user_info/face">
      <meta itemprop="name" content="yinks">
      <meta itemprop="description" content="长路漫漫，半程风雨，半程春">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="静水深流">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          记录一次Vue组件缓存（keep-alive）
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2021-11-03 12:49:45" itemprop="dateCreated datePublished" datetime="2021-11-03T12:49:45+08:00">2021-11-03</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2022-12-06 10:15:57" itemprop="dateModified" datetime="2022-12-06T10:15:57+08:00">2022-12-06</time>
              </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h4 id="先填个坑"><a href="#先填个坑" class="headerlink" title="先填个坑"></a>先填个坑</h4><p>写之前先填个坑，因为一时疏忽，把组将名称和组件components命名重复，导致一个十分诡异的bug，当我数据请求后在我的页面内完完全全复制了一份我当前页面的内容，毫无理由，十分恐怖，当我再次想重现当日情景时发现实现不了!</p>
<h4 id="进入正题"><a href="#进入正题" class="headerlink" title="进入正题"></a>进入正题</h4><h4 id="需求"><a href="#需求" class="headerlink" title="需求"></a>需求</h4><p>首先是从首页跳转到详情页，详情页中有个按钮，点击按钮后会触发一个事件，在PC端，会弹出弹窗展示pdf，而在移动端就需要进入一个新的路由页面了，需要的效果是，从详情页到pdf预览页再返回详情页，详情页中的状态应保持用户最后操作的不变（并不是初始值）。这里PC端是没有任何问题的，因为它只是个弹窗，而重新返回首页再次进入详情页详情页中的数据应该变成初始值， 这就需要使用Vue的组件缓存功能了</p>
<h4 id="实现思路"><a href="#实现思路" class="headerlink" title="实现思路"></a>实现思路</h4><p>经过查找发现网上公布的方法不少，这里记录一下我用的，首先是使用keep-alive包裹住路由出口，因为首页和详情页属于同级路由，但是问题出现了这样无差别的缓存导致从首页进入详情页后，每次都会缓存上次浏览的记录，并且因为一些缓存的问题，首页展示的一些功能也出现了问题，所以需要实现的是路由向前开启缓存，路由退回首页就关闭缓存，我的实现方式如下，下面是代码</p>
<h4 id="应用"><a href="#应用" class="headerlink" title="应用"></a>应用</h4><p>include： - 字符串或正则表达式。只有名称匹配的组件会被缓存。<br>exclude： - 字符串或正则表达式。任何名称匹配的组件都不会被缓存。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// app</span></span><br><span class="line">&lt;template&gt;</span><br><span class="line">  <span class="xml"><span class="tag">&lt;<span class="name">div</span> <span class="attr">id</span>=<span class="string">&quot;app&quot;</span>&gt;</span></span></span><br><span class="line"><span class="xml">  // 仅对UsaChild11组件生效</span></span><br><span class="line"><span class="xml">    <span class="tag">&lt;<span class="name">keep-alive</span> <span class="attr">include</span>=<span class="string">&quot;UsaChild11&quot;</span>&gt;</span></span></span><br><span class="line"><span class="xml">    // 使用路由的meta属性来控制那个路由视口生效</span></span><br><span class="line"><span class="xml">      <span class="tag">&lt;<span class="name">router-view</span> <span class="attr">v-if</span>=<span class="string">&quot;$route.meta.keepAlive&quot;</span>&gt;</span>&lt;/router-view &gt;</span></span><br><span class="line"><span class="xml">    <span class="tag">&lt;/<span class="name">keep-alive</span>&gt;</span></span></span><br><span class="line"><span class="xml">    <span class="tag">&lt;<span class="name">router-view</span> <span class="attr">v-if</span>=<span class="string">&quot;!$route.meta.keepAlive&quot;</span>&gt;</span>&lt;/router-view &gt;</span></span><br><span class="line"><span class="xml">  <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span></span><br><span class="line"><span class="xml"><span class="tag">&lt;/<span class="name">template</span>&gt;</span></span></span><br></pre></td></tr></table></figure>
<p>vue-router</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">   <span class="attr">path</span>: <span class="string">&quot;/QueryArea&quot;</span>,</span><br><span class="line">    <span class="attr">name</span>: <span class="string">&quot;QueryArea&quot;</span>,</span><br><span class="line">    <span class="attr">component</span>: QueryArea,</span><br><span class="line">    <span class="attr">meta</span>: &#123;</span><br><span class="line">        <span class="attr">keepAlive</span>: <span class="literal">true</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;,</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>QueryArea.vue</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 页面信息缓存路由钩子</span></span><br><span class="line">  <span class="function"><span class="title">beforeRouteLeave</span>(<span class="params">to, <span class="keyword">from</span>, next</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">if</span>(to.name == <span class="string">&#x27;Home&#x27;</span> &amp;&amp; <span class="keyword">from</span>.name == <span class="string">&#x27;QueryArea&#x27;</span>)&#123;</span><br><span class="line">      <span class="keyword">from</span>.meta.keepAlive = <span class="literal">false</span></span><br><span class="line">    &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">      <span class="keyword">from</span>.meta.keepAlive = <span class="literal">true</span></span><br><span class="line">    &#125;</span><br><span class="line">    next()</span><br><span class="line">  &#125;,</span><br><span class="line"><span class="comment">// 页面缓存后重新进入触发钩子函数</span></span><br><span class="line">  <span class="function"><span class="title">activated</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="built_in">this</span>.areaValue = <span class="built_in">this</span>.$route.query.market;</span><br><span class="line">  &#125;,</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>因为首页到详情页会动态携带参数展示在页面中，所以以防万一，可以使用keep-alive生效时携带的两个钩子函数<br>activated ：被缓存的页面再次进入时触发<br>deactivated ：缓存的页面首次离开时触发</p>
<blockquote>
<p> 注意一点：activated,deactivated这两个生命周期函数一定是要在使用了keep-alive组件后才会有的，否则则不存在当引入keep-alive的时候，页面第一次进入，钩子的触发顺序created-&gt; mounted-&gt; activated，退出时触发deactivated。当再次进入（前进或者后退）时，只触发activated。</p>
</blockquote>

    </div>

    
    
    
        

<div>
<ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>yinks
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://inkgn.gitee.io/2021/11/03/article28/" title="记录一次Vue组件缓存（keep-alive）">https://inkgn.gitee.io/2021/11/03/article28/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>


      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/Vue/" rel="tag"># Vue</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2021/09/23/article27/" rel="prev" title="【面试题】 js 防抖节流">
      <i class="fa fa-chevron-left"></i> 【面试题】 js 防抖节流
    </a></div>
      <div class="post-nav-item">
    <a href="/2021/11/08/article29/" rel="next" title="Vue 页面预览pdf功能实现（兼容移动端，iOS）">
      Vue 页面预览pdf功能实现（兼容移动端，iOS） <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%85%88%E5%A1%AB%E4%B8%AA%E5%9D%91"><span class="nav-number">1.</span> <span class="nav-text">先填个坑</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E8%BF%9B%E5%85%A5%E6%AD%A3%E9%A2%98"><span class="nav-number">2.</span> <span class="nav-text">进入正题</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E9%9C%80%E6%B1%82"><span class="nav-number">3.</span> <span class="nav-text">需求</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%AE%9E%E7%8E%B0%E6%80%9D%E8%B7%AF"><span class="nav-number">4.</span> <span class="nav-text">实现思路</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%BA%94%E7%94%A8"><span class="nav-number">5.</span> <span class="nav-text">应用</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="yinks"
      src="https://blog-1253246719.cos.ap-chengdu.myqcloud.com/blog/user_info/face">
  <p class="site-author-name" itemprop="name">yinks</p>
  <div class="site-description" itemprop="description">长路漫漫，半程风雨，半程春</div>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://gitee.com/inkgn" title="Gitee → https:&#x2F;&#x2F;gitee.com&#x2F;inkgn" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>Gitee</a>
      </span>
      <span class="links-of-author-item">
        <a href="/2087104694@qq.com" title="E-Mail → 2087104694@qq.com"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">yinks</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://muse.theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Muse</a> 强力驱动
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/muse.js"></script>


<script src="/js/next-boot.js"></script>




  















  

  

</body>
</html>
